# Created by 黄景涛
# DATE: 2025/2/12
import requests

from config.settings import cfg
from utils.auth.V5.saas_login import SmartLogin, InnerLogin
from utils.log.logger import logger
from utils.files.yaml_tool import read_yaml, read_yaml_key, update_yaml_key
from utils.tools.time import get_timestamp

""" 登录相关 """


def login():
    cfg_path = 'config/config.yaml'

    info = cfg.get('auth')
    login_url = info.get('login_url')
    username = info.get('username')
    password = info.get('password')
    is_encrypt = info.get('is_encrypt')

    # ============================================ smart-saas ==================================================
    smart_info = info.get('smart_saas')
    saas_name = smart_info.get('name')
    last_time = smart_info.get('cookie_last_update_time')
    cookie = smart_info.get('cookie')
    # 检查Cookie是否过期，并登录
    if not (cookie and check_update_time(last_time)):
        cookies = SmartLogin(login_url, username, password, saas_name, is_encrypt).login()
        update_yaml_key(cfg_path, 'auth.smart_saas.cookie', cookies)
        update_yaml_key(cfg_path, 'auth.smart_saas.cookie_last_update_time', get_timestamp())
        logger.info(f"【{saas_name:^8}】登录成功， cookies: {cookies}")
    else:
        logger.warning(f"【{saas_name:^8}】登录缓存有效，跳过登录")

    # ============================================ inner-saas ==================================================
    inner_info = info.get('inner_saas')
    saas_name = inner_info.get('name')
    last_time = inner_info.get('cookie_last_update_time')
    cookie = inner_info.get('cookie')
    # 检查Cookie是否过期，并登录
    if not (cookie and check_update_time(last_time)):
        cookies = InnerLogin(login_url, username, password, saas_name, is_encrypt).login()
        update_yaml_key(cfg_path, 'auth.inner_saas.cookie', cookies)
        update_yaml_key(cfg_path, 'auth.inner_saas.cookie_last_update_time', get_timestamp())
        logger.info(f"【{saas_name:^8}】登录成功， cookies: {cookies}")
    else:
        logger.warning(f"【{saas_name:^8}】登录缓存有效，跳过登录")


def check_update_time(timestamp: float, expires: int = 2 * 60 * 60) -> bool:
    """
    检查Cookie的上一次更新时间
    :param timestamp: 待检查的时间戳
    :param expires: cookie的有效时长
    :return:
    """
    if not timestamp:
        return False

    now = get_timestamp()
    diff = int(now - timestamp) + 1
    if diff < expires:
        return True

    return False


if __name__ == '__main__':
    login()

    config_path = 'config/config.yaml'

    # 获取cookie
    ck = read_yaml(config_path).get('auth').get('smart_saas').get('cookie')
    esmv40_api = "http://apps.test-bkee5.cwoa.net/cc-auto/login_info"
    response = requests.get(esmv40_api, cookies=ck, verify=False)
    print(response.json())

    ck = read_yaml(config_path).get('auth').get('inner_saas').get('cookie')
    bkuser_api = "http://bkuser.test-bkee5.cwoa.net/api/v1/web/fields/"
    response = requests.get(bkuser_api, cookies=ck, verify=False)
    print(response.json())
